package com.brooks.demo;

import java.util.Arrays;
import java.util.concurrent.CountDownLatch;

/**
 * 多线程demo---线程不安全
 * @Author: mihutu
 * @Date: 2020/9/28 22:45
 */
public class DemoUnsafe2 {

    private static volatile int n = 0;

    public static void main(String[] args) throws Exception {
        //创建100个线程
        Thread[] threads = new Thread[100];
        //这个是为了等待所有线程完成
        CountDownLatch latch = new CountDownLatch(threads.length);

        for (int i = 0;i<threads.length;i++){
            threads[i] = new Thread(()->{
                for (int j=0;j<10000;j++){
                    n++;
                }
                latch.countDown();
            });
        }
        //启动线程
        Arrays.stream(threads).forEach((t) -> t.start());
        //阻塞线程直到计数等于初始化的值
        latch.await();
        System.out.println(n);
    }
}
